import os, logging, hashlib, re, datetime

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.db import GqlQuery
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required

import model
import gmemsess


__author__="elad"
__date__ ="$Feb 27, 2009"


class Filter(webapp.RequestHandler):

	def post(self):
		""" Save a new filter """
		sess = gmemsess.Session(self)
		filter = sess['filter']
		#logging.debug('filter: %s' % filter.to_string())
		filter.description = self.request.get('filter_desc')
		filter.user = users.get_current_user()
		key = filter.put()
		#logging.debug("Added filter %s" % key.id())
		filters = self.all_my_filters()
		template_values = { 'filters': filters, 'latest': filter, }
		path = os.path.join(os.path.dirname(__file__), 'new_filter.html')
		self.response.out.write(template.render(path, template_values))

	def get(self):
		filters = self.all_my_filters()
		#logging.debug('%d filters found' % len(filters))
		template_values = { 'filters': filters, }
		path = os.path.join(os.path.dirname(__file__), 'filter.html')
		self.response.out.write(template.render(path, template_values))
	
	def all_my_filters(self):
		""" retrieve all saved filters for current user """
		query = model.Filter.all()
		query.filter('user =', users.get_current_user())
		return query.fetch(1000)

	@staticmethod
	def get_filter(request):
		filter_key = request.get('filter')
		if filter_key:			
			filter = model.Filter.get(filter_key)
		else:
			filter = model.Filter()
			filter.logger_ip = request.get('ip_addr')			
			filter.ts = request.get('ts')			
			filter.ts_min = Filter.get_ts_min(request.get('ts'))			
			filter.ts_max = Filter.get_ts_max(request.get('ts'))									
			filter.app_name = request.get('app_name')
			filter.logger_name = request.get('logger_name')			
			filter_severity = request.get('severity')			
			if filter_severity:
				i_severity = int(filter_severity)
				if ((i_severity >= 0) and (i_severity < len(model.LogMessage.Severities))):
					filter.severity = i_severity
					
			filter_dev_mode = request.get('dev_mode')						
			if filter_dev_mode:
				filter.dev_mode = True
			else:
				filter.dev_mode = False
		return filter

	@staticmethod
	def get_ts_min(ts):
		if len(ts) == 0:
			return None
		parts = re.split(r' - ', ts)
		if len(parts) == 2:			
			ts = parts[0]		
		dt = datetime.datetime.strptime(ts, "%m/%d/%Y")
		#logging.info('dt_min: %s' % dt)
		return dt

	@staticmethod
	def get_ts_max(ts):
		if len(ts) == 0:
			return None		
		parts = re.split(r' - ', ts)
		if len(parts) == 2:			
			ts = parts[1]
		ts = "%s 23:59:59" % ts			
		dt = datetime.datetime.strptime(ts, "%m/%d/%Y %H:%M:%S")
		#logging.info('dt_max: %s' % dt)
		return dt
		
	@staticmethod
	def get_filter_conditions(filter):
		conditions = []
		if filter.logger_ip:
			conditions.append(["logger_ip = ", filter.logger_ip, ''])
		if filter.ts_min:
			conditions.append(["timestamp >= ", filter.ts_min, ''])
		if filter.ts_max:
			conditions.append(["timestamp <= ", filter.ts_max, ''])
		if filter.app_name:
			conditions.append(["app_name = ", filter.app_name, ''])
		if filter.logger_name:
			conditions.append(["logger_name = ", filter.logger_name, ''])
		if filter.severity:
			conditions.append(["severity = ", filter.severity, ''])
		if filter.dev_mode:
			conditions.append(["dev_mode = ", filter.severity, ''])			
		return conditions

	@staticmethod
	def get_filter_query(filter):
		query = ''
		if filter.logger_ip:
			query = query + "&ip_addr=%s" % filter.logger_ip
		if filter.ts:
			query = query + "&ts=%s" % filter.ts
		if filter.app_name:
			query = query + "&app_name=%s" % filter.app_name
		if filter.logger_name:
			query = query + "&logger_name=%s" % filter.logger_name
		if filter.severity:
			query = query + "&severity=%s" % filter.severity
		if filter.dev_mode:
			query = query + "&dev_mode=%s" % filter.dev_mode
					
		return query
		

class FilterDelete(webapp.RequestHandler):

	def get(self):
		filter = model.Filter.get(self.request.get('key'))
		filter.delete()
		self.redirect("/filters")


application = webapp.WSGIApplication([('/filters/delete', FilterDelete),
									 ('/filters', Filter),],
                                    debug=True)

def main():
	logging.getLogger().setLevel(logging.DEBUG)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

